package com.wuhunyu.advice;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 课程通知
 *
 * @author wuhunyu
 * @version 1.0
 * @date 2021-01-27 16:24
 */
@Component
@Aspect
public class CourseAdvice {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Pointcut("execution(* com.wuhunyu.controller.EduCourseController.addCourse(..))")
    public void pointAddCourse(){}

    @Pointcut("execution(* com.wuhunyu.controller.EduCourseController.deleteCourse(..))")
    public void pointDeleteCourse(){}

    @After("pointAddCourse()")
    public void countAddCourse() {
        // 判断课程course是否存在
        if (redisTemplate.opsForValue().get("course") == null) {
            redisTemplate.opsForValue().set("course", "1", 1, TimeUnit.DAYS);
            return ;
        }
        // 课程已存在
        redisTemplate.opsForValue().increment("course", 1);
    }

    @After("pointDeleteCourse()")
    public void countDeleteCourse() {
        // 判断课程course是否存在
        if (redisTemplate.opsForValue().get("course") == null) {
            redisTemplate.opsForValue().set("course", "0", 1, TimeUnit.DAYS);
            return ;
        }
        // 课程已存在
        redisTemplate.opsForValue().decrement("course", 1);
    }

}
